const Service = require('egg').Service;
const array=require("../get/array.js");

class DbService extends Service {
    resolver(str) {
        return str.replace(";", " ");
    }
    // whereStr(wheres) { //where: [[key,val,ope="=|in|like"]]
    //     if (wheres[0] && wheres[0][1] !== undefined) {

    //         let str = " where";
    //         wheres.forEach((where, ind) => {
    //             if (where[1] !== undefined) {
    //                 ind != 0 && (str += " and");
    //                 str += ` ${where[0]} ${where[2] ? where[2] : "="} ${where[1]}`
    //             }
    //         });
    //         return str;
    //     }else{
    //         return ""
    //     }
    // }
    async total(tabName, params) {
        let sql = `SELECT count(*) total FROM ${this.resolver(tabName)} `;
        let { where } = params;
        where && (sql += array.toSqlWhereStr(where));
        let end = await this.app.mysql.query(sql);
        return end[0].total;
    }
    async boolean(tabName, whenTrueStr, params) {   //whenTrueStr(判断为真的条件),params: {where:{key:val}}
        let sql = `select (case when ${whenTrueStr} then 'true' else 'false' end) boolean from ${tabName} `;
        let { where } = params;
        where && (sql += array.toSqlWhereStr(where));
        let end = await this.app.mysql.query(sql);
        return end[0].boolean === "true" ? true : false;
    }
}
module.exports = DbService;